var key = '2a09015f33cab1b4e2d84190a0b50db3';  // 此处key要改

var amapFile = {
  AMapWX: function (a) {
    this.key = a.key;
    this.requestConfig = {
      key: a.key,
      s: "rsx",
      platform: "WXJS",
      appname: a.key,
      sdkversion: "1.2.0",
      logversion: "2.0"
    };
    this.MeRequestConfig = {
      key: a.key,
      serviceName: "https://restapi.amap.com/rest/me"
    }
  }
}

amapFile.AMapWX.prototype.getWxLocation = function (a, b) {
  wx.getLocation({
    type: "gcj02",
    success: function (res) {
      res = res.longitude + "," + res.latitude;
      wx.setStorage({
        key: "userLocation",
        data: res
      });
      b(res)
    },
    fail: function (err) {
      wx.getStorage({
        key: "userLocation",
        success: function (res) {
          res.data && b(res.data)
        }
      });
      a.fail({
        errCode: "0",
        errMsg: err.errMsg || ""
      })
    }
  })
};

amapFile.AMapWX.prototype.getWeather = function (params) {
  
  function getCurrentWeather(geoCode) {
    var status = params.type;
    wx.request({
      url: 'https://restapi.amap.com/v3/weather/weatherInfo', 
      data: {
        key: that.key,                       //* 这里的+1挺意义不明的...直接就删了
        city: geoCode,
        extensions: status,
        s: event.s,
        platform: event.platform,
        appname: that.key,
        sdkversion: event.sdkversion,
        logversion: event.logversion
      },
      method: "GET",
      header: {
        "content-type": "application/json"
      },
      success: function (res) {
        if (res.data.status && "1" == res.data.status)
          if (res.data.lives.length) {                          //* 这个条件做了调整 (靠console.log)
            if ((res = res.data.lives) && 0 < res.length) {
              var weather = {     //* 上面删了一行重复功能,下面的赋值格式全改了(console.log看结构)
                city: {
                  text: "\u57ce\u5e02",
                  data: res[0].city
                },
                weather: {
                  text: "\u5929\u6c14",
                  data: res[0].weather
                },
                temperature: {
                  text: "\u6e29\u5ea6",
                  data: res[0].temperature
                },
                winddirection: {
                  text: "\u98ce\u5411",
                  data: res[0].winddirection + "\u98ce"
                },
                windpower: {
                  text: "\u98ce\u529b",
                  data: res[0].windpower + "\u7ea7"
                },
                humidity: {
                  text: "\u6e7f\u5ea6",
                  data: res[0].humidity + "%"
                }
              };
              // weather.liveData = res;
              params.success(weather);
            }
          } else res.data.forecasts && res.data.forecasts[0] && params.success({
            forecast: res.data.forecasts[0]
          });
        else params.fail({
          errCode: res.data.infocode,
          errMsg: res.data.info
        })
      },
      fail: function (err) {
        params.fail({
          errCode: "0",
          errMsg: err.errMsg || ""
        })
      }
    })
  }

  function getGeoCode(geoCode) {

    wx.request({
      url: "https://restapi.amap.com/v3/geocode/regeo?",
      data: {
        key: that.key,
        location: geoCode,
        extensions: "all",
        s: event.s,
        platform: event.platform,
        appname: that.key,
        sdkversion: event.sdkversion,
        logversion: event.logversion
      },
      method: "GET",
      header: {
        "content-type": "application/json"
      },
      success: function (res) {
        console.log(res);
        if (res.data.status && "1" == res.data.status) {
          res = res.data.regeocode;
          if (res.addressComponent) var adCode = res.addressComponent.adcode;
          else res.aois && 0 < res.aois.length && (adCode = res.aois[0].adcode);
          getCurrentWeather(adCode);
        } 
        else params.fail({
          errCode: res.data.infocode,
          errMsg: res.data.info
        })
      },
      fail: function (err) {
        params.fail({
          errCode: "0",
          errMsg: err.errMsg || ""
        })
      }
    })
  }
  
  var that = this,
    event = that.requestConfig;
  
    params.city ? getCurrentWeather(params.city) : that.getWxLocation(params, function (geo) {
    getGeoCode(geo)
  })
};

// 调用高德天气API
var myAmapFun = new amapFile.AMapWX({ key: key });

Page({

  /**
   * 页面的初始数据
   */
  data: {
    disabled: true,
    threshold: 0,
    rule: 'up',
    items: [
      { name: 'up', value: '高于门限报警', checked: 'true' },
      { name: 'down', value: '低于门限报警' },
    ]
  },

  radioChange: function (e) {
    //保存报警规则到当前页面的数据
    if (e.detail.value != "") {
      this.setData({
        rule: e.detail.value
      })
    }
  },

  send: function () {
    //取得门限数据和报警规则
    var that = this;            //* 多了这一步,可以让回调函数使用页面数据(查js里的this的含义)
    myAmapFun.getWeather({
      type: 'base',             //* 请求类型更改(查官方API)
      success: function (res) {
        var tmp = parseFloat(res.temperature.data);  //* 看res的结构,多用了一个parseFloat函数
        //温度高于设置的门限值
        if (tmp > that.data.threshold) {
          if (that.data.rule == "up") {
            //规则为高于门限报警，于是报警
            wx.showModal({
              title: '警报！',         //* 这里及以下四个的tmp多了一个引用(类比看)
              content: `当前温度${tmp}度,高于设定值${that.data.threshold}`
            })
          }
          //规则为低于门限报警，于是不报警
          else if (that.data.rule == "down") {
            wx.showModal({
              title: '提示～',
              content: `当前温度${tmp}度,温度处于正常范围`
            })
          }
        }
        //温度低于设置的门限值
        else if (tmp <= that.data.threshold) {
          //规则为高于门限报警，于是不报警
          if (that.data.rule == "up") {
            wx.showModal({
              title: '提示～',
              content: `当前温度${tmp}度,温度处于正常范围`
            })
          }
          //规则为低于门限报警，于是报警
          else if (that.data.rule == "down") {
            wx.showModal({
              title: '警报！',
              content: `当前温度${tmp}度, 低于设定值${that.data.threshold}`
            })
          }
        }
      },
      fail: function (info) {
        console.error(info)
      }
    })
  },

  //跳转到图片识别的口令验证页面
  validate: function () {
    wx.navigateTo({
      url: '../wifi_station/index/index',
    })
  },


  change: function (e) {
    //当有输入时激活发送按钮，无输入则禁用按钮
    if (e.detail.value != "") {
      this.setData({
        threshold: e.detail.value,
        disabled: false,
      })
    } else {
      this.setData({
        threshold: 0,
        disabled: true,
      })
    }
  }
})